<template>
	<view class="container">
		<view class="picker">
			<view class="picker-item">
				<u-button>
					<view class="flex-start-center">
                        <view class="online-circle"></view>
                        <text style="font-size: 13px;white-space: nowrap;">{{ currentTime }}</text>
					</view>
				</u-button>
			</view>
            <view class="picker-item">
                <u-picker :show="workshopPickerState" @cancel="workshopPickerState = false" @close="workshopPickerState = false" :closeOnClickOverlay="true" @confirm="onWorkShop" :columns="[workshopList]" keyName="name"></u-picker>
                <u-button @click="workshopPickerState = true">
                    <view class="flex-start-center">
                        <text class="item-gap">{{searchParams.workshopName}}</text>
                        <u-icon name="arrow-down"></u-icon>
                    </view>
                </u-button>
            </view>
			<view class="picker-item">
				<u-picker :show="groupPickerState" @cancel="groupPickerState = false" @close="groupPickerState = false" :closeOnClickOverlay="true" @confirm="onConfirmTeam" :columns="[scheduleGroupList]" keyName="groupName"></u-picker>
				<u-button @click="groupPickerState = true">
				<view class="flex-start-center">
					<text class="item-gap">{{searchParams.scheduleGroupName}}</text>
					<u-icon name="arrow-down"></u-icon>
				</view>
				</u-button>
			</view>
			<view class="picker-item">
				<u-button type="primary" @click="onShowBtn" icon="account-fill" text="排班状况"></u-button>
			</view>
		</view>
		<view>
		    <jk-table width="60" stripe :height="tableHeight - 110" :cell-style="cellStyle" :table-header="tableHeader" :table-data="tableData"></jk-table>
		</view>
        <post-emp-detail-modal
            :searchParams="searchParams"
            :state="postEmpDetailModalState"
            @on-visible-change="onVisibleChange"
        ></post-emp-detail-modal>
	</view>
</template>

<script>
	import jkTable from "../../jk-components/jk-table";
	import loadingMore from "../../mixins/loading-more.js";
    import {formatTime, showLoading} from "../../utils/jk-utils.js";
    import {
        systemUserColumnConfigGet,
        reportProductionOrderMachineGroupList,
        workforceManagementScheduleGroupGetGroup,
        reportProductionOrderMachineGroupNoEmpList
    } from '../../api/index.js';
    import postEmpDetailModal from "./postEmpDetailModal";
    let lineObj = {};
	export default {
		mixins: [loadingMore],
		components: {
            postEmpDetailModal,
			jkTable,
		},
		data(){
			return {
                postEmpDetailModalState: false,
                lineObj: {},
                bgColors: ['#19be6b', '#2d8cf0'],
                borderColors: ['#3fda8c', '#5cadff'],
				interVal: {},
				tableHeader:null,
				tableData:null,
				tableHeight: 0,
				workshopList: [],
				teamOrGroup: [],
				searchParams: {
					workshopId: '',
					workshopName:'',
                    scheduleGroupId:''
				},
                workshopPickerState: false,
				groupPickerState:false,
                scheduleGroupList: [],
                checkDataItem: {},
                currentTime: '',
                currentTimer: {}
			}
		},
		onHide(){
			this.clearInterVal();
		},
		onUnload() {
			this.clearInterVal();
		},
		onShow(){
			this.landscape();
			// 用于直接回到手机桌面再进入时重新启动定时任务
            this.runData();
        },
		onLoad(){
              this.getDependentData();
		},
		methods: {
		    onShowBtn() {
		        this.postEmpDetailModalState = true;
            },
            onVisibleChange(e) {
                this.postEmpDetailModalState = e;
            },
            cellStyle({ row, column }) {
                let styleCfg = {};
                /*if (Object.keys(this.checkDataItem).length && (column.keyName === this.checkDataItem.keyName || row.isCheck)) {
                    styleCfg = {
                        boxShadow: 'inset 0 0 0px 0.5px #ff9900',
                        color: '#fff',
                        background: '#ff9900'
                    };
                } else {

                }*/
                // 1-2线 并条 蓝色背景
                if (row.productionLineCode === '1-2#' && (row.processCode === 'TB' || row.processCode === 'MB')) {
                    styleCfg = {
                        boxShadow: 'inset 0 0 0px 0.5px #5cadff',
                        backgroundImage: 'none',
                        backgroundColor: '#1890ff',
                        color: '#fff'
                    };
                } else if (row.productionLineCode === '6#' && row.processCode === 'CS') {
                    // 六线 粗纱 蓝色背景
                    styleCfg = {
                        boxShadow: 'inset 0 0 0px 0.5px #5cadff',
                        backgroundImage: 'none',
                        backgroundColor: '#1890ff',
                        color: '#fff'
                    };
                } else {
                    styleCfg = {
                        backgroundColor: lineObj[row.productionLineId].bgColor,
                        backgroundImage: 'none',
                        boxShadow: `inset 0 0 0px 0.5px ${lineObj[row.productionLineId].borderColor}`,
                        color: '#fff'
                    };
                }
                return styleCfg;
            },
            async getDependentData(){
				showLoading(true);
                this.workshopList = getApp().globalData.defaultWorkshop.list;
                if (!this.searchParams.workshopId){
                    // 默认前纺车间
                    let workshopItem = this.workshopList.find(x => x.name.indexOf('前纺') !== -1) || {};
                    this.$set(this.searchParams, 'workshopId', workshopItem.id || getApp().globalData.defaultWorkshop.id);
                    this.$set(this.searchParams, 'workshopName', workshopItem.name || getApp().globalData.defaultWorkshop.name);
                }
                this.currentTime = formatTime(Date.now());
                await this.getSystemInfo();
				await this.getTableHeaderRequest();
				await this.getRealTimeGroupRequest();
				await this.getListRequest();
				showLoading(false);
				this.runData();
			},
            getRealTimeGroupRequest() {
                if (this.searchParams.workshopId) {
                    return workforceManagementScheduleGroupGetGroup({
                        workshopId: this.searchParams.workshopId
                    }).then(res => {
                        if (res.data.status === 200) {
                            const resData = res.data.res || [];
                            this.scheduleGroupList = resData;
                            if (!this.scheduleGroupList.find(x => x.id === this.searchParams.scheduleGroupId)) {
                                let scheduleGroupItem = {};
                                if (resData && resData.length) {
                                    scheduleGroupItem = this.scheduleGroupList.length ? this.scheduleGroupList[0] : {};
                                }
                                this.$set(this.searchParams, 'scheduleId', scheduleGroupItem.scheduleId);
                                this.$set(this.searchParams, 'scheduleGroupId', scheduleGroupItem.id);
                                this.$set(this.searchParams, 'scheduleGroupName', scheduleGroupItem.groupName);
                                this.getListRequest();
                            }
                        }
                    });
                }
            },
			runData() {
                clearInterval(this.interVal);
                clearInterval(this.currentTimer);

				this.currentTimer = setInterval(() => {
                    this.currentTime = formatTime(Date.now());
				}, 1000);
                this.interVal = setInterval(() => {
                    this.getListRequest();
                }, 10000);
			},
			clearInterVal() {
                clearInterval(this.currentTimer);
                clearInterval(this.interVal);
			},
			onSearchBtn(){
				this.getListRequest();
			},
			onWorkShop(e){
				this.searchParams.workshopId = e.value[0].id
				this.searchParams.workshopName = e.value[0].name
                this.workshopPickerState = false
                if(this.searchParams.workshopId){
                    this.getRealTimeGroupRequest();
				}
			},
			onConfirmTeam(e){
				this.searchParams.scheduleGroupName = e.value[0].groupName
				this.groupPickerState = false
                this.getListRequest();
			},
			// 横屏展示
			landscape() {
				uni.setPageOrientation({
					orientation: 'landscape'
				});
			},
			/**
			 * 查询列表
			 * */
			 getListRequest () {
				if(this.searchParams.workshopId && this.searchParams.scheduleGroupId){
				    let params = JSON.parse(JSON.stringify(this.searchParams));
				    delete params.workshopName;
                    return reportProductionOrderMachineGroupNoEmpList(this.searchParams).then(res=>{
                        lineObj = {};
                        this.tableData = res.data.res ? res.data.res.map(x => {
                            if (Object.keys(this.checkDataItem).length && x.machineId === this.checkDataItem.id) {
                                this.$set(x, 'isCheck', true);
                            }
                            if(x.productionLineName){
                                x.productionLineName = x.productionLineName + '-' + x.processName
                            }
                            if (!lineObj[x.productionLineId]) {
                                idx = 0;
                                lineObj[x.productionLineId] = {
                                    bgColor: this.bgColors[idx],
                                    borderColor: this.borderColors[idx],
                                    productionLineName: x.productionLineName
                                };
                            }
                            return x;
                        }) : [];
                        let idx = 0;
                        for (const item in lineObj) {
                            if (idx >= 2) idx = 0;
                            idx++;
                            lineObj[item].bgColor = this.bgColors[idx - 1];
                            lineObj[item].borderColor = this.borderColors[idx - 1];
                        }
					})
				}
			},
			getTableHeaderRequest () {
				systemUserColumnConfigGet({
					path:'frontEmpAndMachineMonitor',
					filterShow:true
				}).then(res=>{
					if(res.data.status === 200){
					    let resData = res.data.res;
					    let arr = [];
					    if (resData && resData.columnConfigList) {
                            arr = resData.columnConfigList.find(x => x.code === 'wechat') ? resData.columnConfigList.find(x => x.code === 'wechat').itemList : [];
                        }
						this.tableHeader = arr.map(x => {
							x.key = x.keyName;
							return x;
						});
					}
				})
			},
			getSystemInfo() {
				let _this = this;
				return new Promise((resolve,reject)=>{
					uni.getSystemInfo({
						success(res) {
							resolve();
							_this.windowHeight = res.windowHeight;
							_this.tableHeight = res.windowWidth;
						},
						error(err){
							reject(err)
						}
					});
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
    .online-circle {
        width: 6px;
        height: 6px;
        background: #2d8cf0;
        border-radius: 50%;
        animation: onLineAn 1.5s infinite linear;
        margin-right: 4px;
    }
    @keyframes onLineAn {
        0% {
            opacity: 1;
        }
        50% {
            opacity: .3;
        }
        100% {
            opacity: 1;
        }
    }
	.container{
		background-color: #f8f8f9;
		.picker{
			width: 100%;
			display: flex;
			justify-content: space-between;
			.picker-item{
				flex: 1;
			}
		}
	}
</style>
